package Thread;

public class MyBlockingqueue {
    public int[] capacity = new int[10];
    public int head = 0;
    public int tail = 0;
    public int useSize = 0;

    Object locker = new Object();
    public void put(int data) throws InterruptedException {
        synchronized (locker) {
            //判断是否满了
            if (useSize == capacity.length) {
                locker.wait();
            }
            capacity[tail] = data;
            tail = (tail + 1) % capacity.length;
            useSize++;
            locker.notify();
        }

    }

    public int take () throws InterruptedException {
        synchronized (locker) {
            //判断是否为空
            if (useSize == 0) {
                locker.wait();
            }
            int tmp = capacity[head];
            head = (head + 1) % capacity.length;
            useSize--;
            locker.notify();
            return tmp;
        }
    }

    public static void main(String[] args) {
        MyBlockingqueue q1 = new MyBlockingqueue();

        Thread t1 = new Thread(() -> {
            for(int i = 0;i < 50;i++) {
                try {
                    q1.put(i);
                    System.out.println("输入了 " + i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (true){
                try {
                    System.out.println("抛出了 " + q1.take());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
